package com.vgemv.jsutilitysdk.Page.JsPageGroupView;

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;

import com.vgemv.jsutilitysdk.JsThread.JsThreadManager;

import java.util.ArrayList;

public class JsPageGroupView extends HorizontalScrollView implements IJsPageGroupView{

    public LinearLayout mll_root;
    public JsPageGroupViewCallback mCallback;
    public JsPageGroupViewVm mVm;
    private ArrayList<FrameLayout> mal_pageView = new ArrayList<>();
    public int currentPage = 0;

    private int touchStartX;
    private int touchEndX;

    //滑动的阈值
    private  int velocityThreshhold = 7000;

    //是否滚动了 down事件标明滚动了.
    private boolean mb_isScrolled = false;
    //松开时的滚动速率
    private int velocityAfterTouchUp = 0;

    public JsPageGroupView(Context context,@NonNull JsPageGroupViewCallback callback) {
        super(context);
        mCallback = callback;
                if(mCallback != null) {
                    mVm = mCallback.jsPageGroupViewSetVm(JsPageGroupView.this);
                }
                if(mVm == null) {
                    mVm = new JsPageGroupViewVm();
                }
                setupUiIfNeeded();
    }


    public void setupUiIfNeeded() {
        setupUi();
    }

    private void setupUi() {
        JsPageGroupViewVm vm = mVm;
        //设置scrollView的样式
        setHorizontalScrollBarEnabled(false);
        if(vm.backgroundColor != null) {
            setBackgroundColor(vm.backgroundColor);
        }

        //初始化rootView
        Context context = getContext();
        mll_root = new LinearLayout(context);
        int pageWidth = mVm.pageWidth;
        ViewGroup.LayoutParams lp_root = new ViewGroup.LayoutParams(pageWidth*vm.pageCount, ViewGroup.LayoutParams.MATCH_PARENT);
        mll_root.setLayoutParams(lp_root);
        addView(mll_root);

        for(int i = 0;i<vm.pageCount;i++) {
            FrameLayout pageView = new FrameLayout(getContext());
            pageView.setId(View.generateViewId());
            mal_pageView.add(pageView);

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(pageWidth, ViewGroup.LayoutParams.MATCH_PARENT);
            pageView.setLayoutParams(lp);
            mll_root.addView(pageView);

            mCallback.jsPageGroupViewSetPageViewContent(JsPageGroupView.this,pageView,i);
        }
    }

    @Override
    public void choosePage(int pageIndex) {
        if(currentPage != pageIndex) {
            FrameLayout pageViewContainer = mal_pageView.get(pageIndex);
            mCallback.jsPageGroupViewScrollToNewPage(JsPageGroupView.this,pageViewContainer,pageIndex);
        }
        currentPage = pageIndex;
        scrollTo(mVm.pageWidth * pageIndex, 0);
    }

    @Override
    public FrameLayout pageForIndex(int index) {
        return mal_pageView.get(index);
    }

    /**
     * 键盘的事件
     * @param ev
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                touchStartX = getScrollX();
                mb_isScrolled = true;
                break;
            }
            case MotionEvent.ACTION_UP: {
                touchEndX = getScrollX();
                velocityAfterTouchUp = 0;
                //当前位置最靠近的页面
                final int pageNum = (touchEndX + mVm.pageWidth / 2) / mVm.pageWidth;
                //当前位置,已经完全滑过的页数.
                final int pageScrolled = touchEndX/ mVm.pageWidth;
//                JsLogManager.logc_d("JsPageGroupView/onTouchEvent", "MotionEvent:ACION_UP");
                JsThreadManager.runInMainThreadAtNextRunloop(new Runnable() {
                    @Override
                    public void run() {
//                        JsLogManager.logc_d("JsPageGroupView/onTouchEvent", "MotionEvent:ACION_UP next runloop");

                        //如果速率=0,则返回到
                        if(velocityAfterTouchUp >= velocityThreshhold) {
                            choosePage(pageScrolled+1);
                        }
                        else if(velocityAfterTouchUp <= -velocityThreshhold) {
                            choosePage(pageScrolled);
                        }
                        else {
                            choosePage(pageNum);
                        }
                    }
                });
                break;
            }
        }
        return super.onTouchEvent(ev);
    }

    /**
     *    runloop_1 停止滑动时,事件响应顺序
     *    1,onTouchEvent_1:MotionEvent.ActionUp
     *    2,fing_1,如果有速度会调用fing,所以可以在此时设置如果 > 200则到下一页,小于<200则到上一页,否则回到当前页.
     *    runloop2
     *    1,onTouchEvent_1派发事件
     *    2,fling_2,fling1派发事件.
     *     onTouchEvent,必须调用super的,才会触发该方法.
     *     将惯性设置为很小,阻止惯性.
     *     需要停止的时候有速度才会调用该方法
     * @param velocity
     */
    @Override
    public void fling(final int velocity) {
//        JsLogManager.logc_d("JsPageGroupView/fling","The velocity is %d",velocity);
        velocityAfterTouchUp = velocity;
//        super.fling(velocity / 1000);
    }

}
